import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from './auth'
import router from '@/router'
import store from '@/store'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 解构后端字段
    // success: 接口是否成功
    // data: 接口数据
    // message: 接口提示文案
    const { success, data, message } = response.data
    if (success) {
      return data
    } else {
      // 错误提示用户
      Message.warning(message)
      // 手动抛出错误
      return Promise.reject(message)
    }
  },
  error => {
    if (error.response.status === 401) {
      // 1. 清理失效的数据
      store.commit('user/removeUserInfo')
      // 2. 跳回到登录
      router.push({
        path: '/login'
      })
    }
    return Promise.reject(error)
  }
)

export default service
